package com.mantru.iotpot.dishes;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cook.CookActivity;
import com.mantru.iotpot.Cook.PutFoodActivity;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.LoadingDialogUtil;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.EventMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

public class FinishRecordActivity extends AppCompatActivity {
    private ApplicationClass ac;
    private Dialog dialog1;
    private int vegetableId;
    private int ErrorGripper = 0;//0表示机械臂没有故障，1表示机械臂出现故障
    private String TAG = "FinishRecordActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finish_record);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        EventBus.getDefault().register(this);
        Button save = findViewById(R.id.finish_record_save);
        Button nosave = findViewById(R.id.finish_record_nosave);
        save.setOnClickListener(v -> {//保存菜谱并出菜
            String json_data = ac.Developing_Save();
            Log.d("JsonParser", "json_data: " + json_data);
            try {
                JSONObject jsonObject = new JSONObject(json_data);
                boolean success = jsonObject.getBoolean("success");
                if (success){
                    vegetableId = jsonObject.getInt("vegetable_id");
                    int specId = jsonObject.getInt("spec_id");
                    // 打印结果
                    Log.d("JsonParser", "success: " + success);
                    Log.d("JsonParser", "vegetable_id: " + vegetableId);
                    Log.d("JsonParser", "spec_id: " + specId);
                    boolean result = ac.Cooking_PourOut();//调用出菜指令
                    if (result){
                        if (ErrorGripper == 0){
                            Intent intent = new Intent(new Intent(this, DishesPutFoodActivity.class));
                            intent.putExtra("vegetableId",vegetableId);
                            startActivity(intent);
                            finish();
                        } else if (ErrorGripper == 1) {
                            ShowCheakDialog(1);
                        }
                    }else {
                        //Toast.makeText(this, "出菜失败", Toast.LENGTH_SHORT).show();
                        ToastUtils.show(this, "出菜失败");
                    }
                }else {
                    //Toast.makeText(this, "保存菜谱失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "保存菜谱失败");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("JsonParser", "解析 JSON 数据时出错: " + e.getMessage());
            }
        });
        nosave.setOnClickListener(v -> {//不保存菜谱并出菜
            boolean result = ac.Cooking_PourOut();//调用出菜指令
            if (result){
                if (ErrorGripper == 0){
                    startActivity(new Intent(this, PutFoodActivity.class));
                    finish();
                } else if (ErrorGripper == 1) {
                    ShowCheakDialog(2);
                }
            }else {
                //Toast.makeText(this, "出菜失败", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "出菜失败");
            }
        });
    }

    private void ShowCheakDialog(int type){
        // 如果弹窗已经显示，则不重复显示
        if (dialog1 != null && dialog1.isShowing()) {
            return;
        }
        // 创建自定义对话框
        dialog1 = new Dialog(this);
        dialog1.setContentView(R.layout.manual_cheak_dialog); // 设置对话框的布局

        Button stop = dialog1.findViewById(R.id.manual_cheak_dialog_stop);
        Button low = dialog1.findViewById(R.id.manual_cheak_dialog_low);
        Button rotate = dialog1.findViewById(R.id.manual_cheak_dialog_rotate);

        stop.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Stop();
            ac.SaveLog("用户点击了炒菜爪手动寻位的停止按钮");
        });

        low.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Slow();
            ac.SaveLog("用户点击了炒菜爪手动寻位的低速按钮");
        });

        rotate.setOnClickListener(v -> {
            if (type == 1){//出菜并保存
                ac.Device_SendCommand_Gripper_OK();
                ac.SaveLog("用户点击了炒菜爪手动寻位的确认按钮");
                dialog1.dismiss();
                Intent intent = new Intent(new Intent(this, DishesPutFoodActivity.class));
                intent.putExtra("vegetableId",vegetableId);
                startActivity(intent);
                finish();
            } else if (type == 2) {//出菜并不保存
                ac.Device_SendCommand_Gripper_OK();
                ac.SaveLog("用户点击了炒菜爪手动寻位的确认按钮");
                dialog1.dismiss();
                startActivity(new Intent(this, PutFoodActivity.class));
                finish();
            }
        });
        // 关键代码：设置窗口背景透明
        if (dialog1.getWindow() != null) {
            dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        dialog1.setCanceledOnTouchOutside(false);

        // 显示对话框
        dialog1.show();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage event){
        if (event.id == EventMessage.MSG_ID_ErrorGripper){//收到了机械臂出现故障的消息
            ErrorGripper = 1;
            ac.SaveLog(TAG + " 界面接收到机械臂出现故障的事件");
        }
    }
}